package com.ganzi.ganziserver.shiro;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {


            ModelAndView mv = new ModelAndView();
            FastJsonJsonView view = new FastJsonJsonView();
            Map<String, Object> attributes = new HashMap<String, Object>();
            try{
                if (ex instanceof UnauthenticatedException) {
                    attributes.put("code", "1000001");
                    attributes.put("msg", "未登录");
                    httpServletResponse.sendError(4001);
                } else if (ex instanceof UnauthorizedException) {
                    attributes.put("code", "1000002");
                    attributes.put("msg", "用户无权限");
                } else {
                    attributes.put("code", "1000003");
                    attributes.put("msg", "登录过期");
                    httpServletResponse.sendError(4001);
                }
            }catch (Exception e){
                attributes.put("code", "1000004");
                attributes.put("msg", "系统异常");
            }
            view.setAttributesMap(attributes);
            mv.setView(view);
            return mv;


    }
}
